<?php

namespace core;
defined('BY_JYA') or exit('error');
class module{
	public function plugin_install($module){
		//安装数据表
		if(!empty($module['install'])){
			pdo_query($module['install']);
		}
		//插入初始化数据
		if($module['install_data']){
			foreach($module['install_data'] as $table=>$data){
				$check=pdo_count($table);
				if($check){
					continue;
				}
				foreach($data as $row){
					pdo_insert($table,$row);
				}
			}
		}
		$data=array_fields(array('name','title','type','style','intype','version','description','covers','menus','diypage','mobile_menus','release','istakeover','link','custom_access_type','is_legao','diy_legao','msgtpl'),$module);
		if(!$data['name']){
			exi('插件参数错误，安装失败！','error');
		}
		if($module['image']){
			$image=file_get_contents($module['image']);
			$data['image']=cfc('files')->source_save($image,'image','jpg','插件“'.$module['title'].'”logo');
		}
		$data['cloud_id']=$id;
		pdo_insert('core_plugins',$data);
		$this->insert_more($data,$module);
		return true;
	}
	public function get_filemenus($name) {
		$menu_file=ROOT_PLUGIN.$name.'/model/menu.php';
		if(is_file($menu_file)){
			$getmenu=plugin($name)->menu();
		}
		$menus=array();
		if($getmenu){
			foreach($getmenu as $gv){
				foreach($gv['child'] as $c){
					//如果是三级
					if($c['child']){
						foreach($c['child'] as $x){
							$menus[]=array(
								'title'=>$x['title'],
								'name'=>$x['url'],
							);
						}
					}
					//如果是二级
					if($c['title'] && $c['url']){
						$menus[]=array(
								'title'=>$c['title'],
								'name'=>$c['url'],
						);
					}
				}
			}
		}
		return $menus;
	}
	public function insert_more($data,$configdata) {
		model('core/msg_tpl')->check_tpl($data['name']);
		if($data['type']==4){
			$id=pdo_insertid();
			$old_insert=array(
				'name'=>$data['name'],
				'need_menu'=>$configdata['need_menu'],
				'setting'=>$configdata['application']['setting'],
			);
			pdo_insert('core_old_plugins',$old_insert);
		}
		
		if($configdata['permissions']){
			foreach($configdata['permissions'] as $perm){
				$new_perm=array_fields(array('type','title','action','op'),$perm);
				$new_perm['plugin']=$data['name'];
				pdo_insert('core_plugin_permissions',$new_perm);
			}
		}else{
			//插入基础权限集
			$permission=array(
				'type'=>1,
				'plugin'=>$data['name'],
				'title'=>$data['title'],
				'image'=>$data['image'],
			);
			pdo_insert('core_plugin_permissions',$permission);
		}
		if($configdata['subscribe']){
			foreach($configdata['subscribe'] as $subscribe){
				$data=array(
					'subscriber'=>$subscribe['subscriber'],
					'plugin'=>$subscribe['plugin'],
					'event'=>$subscribe['event'],
				);
				$check=pdo_getcolumn('core_plugin_subscribe',$data,'id');
				if(!$check){
					pdo_insert('core_plugin_subscribe',$data);
				}
			}
		}
	}
	public function update_more($plugin,$configdata) {
		model('core/msg_tpl')->check_tpl($plugin['name']);
		if($plugin['type']==4){
			$update=array(
				'need_menu'=>$configdata['need_menu'],
				'setting'=>$configdata['application']['setting'],
			);
			pdo_update('core_old_plugins',$update,array('name'=>$plugin['name']));
		}
		//检测权限数据是否已添加，如果没有，则添加之
		if(!pdo_getcolumn('core_plugin_permissions',array('plugin'=>$plugin['name']),'id')){
			$permission=array(
				'type'=>1,
				'plugin'=>$plugin['name'],
				'title'=>$plugin['title'],
				'image'=>$plugin['image'],
			);
			pdo_insert('core_plugin_permissions',$permission);
		}
		//检测更新权限数据
		if($configdata['permissions']){
			foreach($configdata['permissions'] as $perm){
				$check=pdo_getcolumn('core_plugin_permissions',array('plugin'=>$configdata['name'],'action'=>$perm['action'],'op'=>$perm['op']),'id');
				if($check){
					pdo_update('core_plugin_permissions',array('type'=>$perm['type'],'title'=>$perm['title']),array('id'=>$check));
				}else{
					$new_perm=array_fields(array('type','title','action','op'),$perm);
					$new_perm['plugin']=$configdata['name'];
					pdo_insert('core_plugin_permissions',$new_perm);
				}
			}
		}
		//检测更新插件事件订阅
		if($configdata['subscribe']){
			foreach($configdata['subscribe'] as $subscribe){
				$data=array(
					'subscriber'=>$subscribe['subscriber'],
					'plugin'=>$subscribe['plugin'],
					'event'=>$subscribe['event'],
				);
				$check=pdo_getcolumn('core_plugin_subscribe',$data,'id');
				if(!$check){
					pdo_insert('core_plugin_subscribe',$data);
				}
			}
		}
		//插件初始化数据
		if($configdata['install_data']){
			foreach($configdata['install_data'] as $table=>$data){
				$check=pdo_count($table);
				if($check){
					continue;
				}
				foreach($data as $row){
					pdo_insert($table,$row);
				}
			}
		}
	}
	public function int_update($config_data) {
		$bindings=array(
			'page' => $config_data['bindings']['page'],
			'cover' => $config_data['bindings']['cover'],
			'rule' => $config_data['bindings']['rule'],
			'menu' => $config_data['bindings']['menu'],
			'home' => $config_data['bindings']['home'],
			'profile' => $config_data['bindings']['profile'],
			'system_welcome' => $config_data['bindings']['system_welcome'],
			'webapp' => $config_data['bindings']['webapp'],
			'phoneapp' => $config_data['bindings']['phoneapp'],
		);
		if(count($config_data['bindings']['menu'])<2){
			$need_menu=0;
		}else{
			$need_menu=1;
		}
		return array(
			'name' => $config_data['application']['identifie'],
			'title' => $config_data['application']['name'],
			'version' => $config_data['application']['version'],
			'type' =>$config_data['application']['type'],
			'is_legao' => $config_data['application']['is_legao']?1:0,
			'style'=>$config_data['application']['style'],
			'intype'=>$config_data['application']['intype'],
			'istakeover'=>intval($config_data['application']['istakeover']),
			'basic'=>$config_data['application']['basic'],
			'diypage'=>$config_data['application']['diypage'],
			'ability' => $config_data['application']['ability'],
			'description' => $config_data['application']['description'],
			'author' => $config_data['application']['author'],
			'url' => $config_data['application']['url'],
			'settings'  => intval($config_data['application']['setting']),
			'handles' => ijson_encode(is_array($config_data['platform']['handles']) ? $config_data['platform']['handles'] : array()),
			'isrulefields' => intval($config_data['platform']['isrulefields']),
			'iscard' => intval($config_data['platform']['iscard']),
			'bindings'=>ijson_encode($bindings),
			'menus' => ijson_encode($config_data['bindings']['menu']),
			'covers' => ijson_encode($config_data['bindings']['cover']),
			'shortcut' => ijson_encode($config_data['bindings']['shortcut']),
			'function' => ijson_encode($config_data['bindings']['function']),
			'issystem' => 0,
			'need_menu' => $need_menu,
		);
	}
	public function run_xmlsql($manifest, $runtype) {
		if (!in_array($runtype, array('install', 'upgrade'))) {
			return false;
		}
		$pluginname = $manifest['application']['identifie'];
		$plugin_path = ROOT_PLUGIN . $pluginname . '/';
		if (!empty($manifest[$runtype])) {
			if (strexists($manifest[$runtype], '.php')) {
				if (file_exists($plugin_path . $manifest[$runtype])) {
					include_once $plugin_path . $manifest[$runtype];
				}
			} else {
				$manifest[$runtype]=str_replace('{table_pre}',TABLE_PRE,$manifest[$runtype]);
				pdo_run($manifest[$runtype]);
			}
		}
		return true;
	}
	public function unrun_xmlsql($manifest) {
		$plugin_path = ROOT_PLUGIN . $pluginname . '/';
		if (empty($manifest)) {
			return false;
		} else {
			if (!empty($manifest['uninstall'])) {
				if (strexists($manifest['uninstall'], '.php')) {
					if (file_exists($modulepath . $manifest['uninstall'])) {
						require($modulepath . $manifest['uninstall']);
					}
				} else {
					$manifest['uninstall']=str_replace('{table_pre}',TABLE_PRE,$manifest['uninstall']);
					pdo_run($manifest['uninstall']);
				}
			}
		}
		return true;
	}
	public function local_plugins() {
		if(function_exists('scandir')){
			$plugin_dirs=scandir(ROOT_PLUGIN);
		}else if(function_exists('glob')){
			$isglob=true;
			$plugin_dirs=glob(ROOT_PLUGIN . '*');
		}else{
			exi('检查本地应用需要用到“scandir”函数或“glob”函数，请联系服务器管理员开启支持！','error');
		}
		$local_uninstall=array();
		foreach ($plugin_dirs as $plugin_name) {
			if(!$plugin_name || $plugin_name=='.' || $plugin_name=='..'){
				continue;
			}
			if($isglob){
				$plugin_name=pathinfo($plugin_name, PATHINFO_BASENAME);
			}
			$config_file=ROOT_PLUGIN.$plugin_name.'/manifest.xml';
			if (!file_exists($config_file)) {
				continue;
			}
			$getplugin=pdo_get('core_plugins',array('name'=>$plugin_name),array('cloud_id','name','version'));
			if($getplugin['cloud_id']){
				continue;
			}
			$manifest = $this->get_manifest($plugin_name);
			$pluginupdata = array(
				'name' => $plugin_name,
				'has_new_version' => 0,
				'install_status' => 0,
				'logo' => $manifest['application']['logo'],
				'version' => $manifest['application']['version'],
				'old_version'=>$getplugin['version'],
				'title' => $manifest['application']['name'],
			);
			if (!empty($manifest['platform']['supports'])) {
				foreach (array('app', 'wxapp', 'webapp', 'android', 'ios', 'system_welcome', 'aliapp', 'baiduapp', 'toutiaoapp') as $item) {
					if (in_array($item, $manifest['platform']['supports'])) {
						if ($item == 'app') {
							$item = 'account';
						}
						if ($item == 'system_welcome') {
							$item = 'welcome';
						}
						if ($item == 'android' || $item == 'ios') {
							$item = 'phoneapp';
						}
						$pluginupdata["{$item}_support"] = 1;
					}
				}
			}
			if ($getplugin) {
				$pluginupdata['install_status']=1;
				if($manifest['application']['version']>$getplugin['version']){
					$pluginupdata['has_new_version']=1;
				}
			}
			$local_uninstall[]=$pluginupdata;
		}
		return $local_uninstall;
	}
	public function get_manifest($plugin_name) {
		$manifest = ROOT_PLUGIN. $plugin_name;
		$filename = $manifest . '/manifest.xml';
		if (!file_exists($filename)) {
			return array();
		}
		$xml = file_get_contents($filename);
		$xml = $this->parse_manifest($xml);
		if (!empty($xml)) {
			if (file_exists($manifest . '/icon.jpg')) {
				$xml['application']['logo'] = tomedia('../addons/'.$plugin_name . '/icon.jpg');
			}elseif (file_exists($manifest . '/preview-custom.jpg')) {
				$xml['application']['preview'] = tomedia('../addons/'.$plugin_name  . '/preview-custom.jpg');
			} else {
				$xml['application']['preview'] = tomedia('../addons/'.$plugin_name  . '/preview.jpg');
			}
			if (empty($xml['platform']['supports'])) {
				$xml['platform']['supports'][] = 'app';
			}
		}
		return $xml;
	}
	public function parse_manifest($xml) {
		if (!strexists($xml, '<manifest')) {
			$xml = base64_decode($xml);
		}
		if (empty($xml)) {
			return array();
		}
		$domDocument = new \DOMDocument();
		$domDocument->loadXML($xml);
		$domroot = $domDocument->getElementsByTagName('manifest')->item(0);
		if (empty($domroot)) {
			return array();
		}
		$versionCode = explode(',', $domroot->getAttribute('versionCode'));
		$manifest['versions'] = array();
		if (is_array($versionCode)) {
			foreach ($versionCode as $v) {
				$v = trim($v);
				if (!empty($v)) {
					$manifest['versions'][] = $v;
				}
			}
			$manifest['versions'] = array_unique($manifest['versions']);
		}
		$manifest['install'] = $domroot->getElementsByTagName('install')->item(0)->textContent;
		$manifest['uninstall'] = $domroot->getElementsByTagName('uninstall')->item(0)->textContent;
		$manifest['upgrade'] = $domroot->getElementsByTagName('upgrade')->item(0)->textContent;
		$application = $domroot->getElementsByTagName('application')->item(0);
		if (empty($application)) {
			return array();
		}
		$manifest['application'] = array(
			'name' => trim($application->getElementsByTagName('name')->item(0)->textContent),
			'identifie' => trim($application->getElementsByTagName('identifie')->item(0)->textContent),
			'version' => trim($application->getElementsByTagName('version')->item(0)->textContent),
			'type' => trim($application->getElementsByTagName('type')->item(0)->textContent),
			'ability' => trim($application->getElementsByTagName('ability')->item(0)->textContent),
			'description' => trim($application->getElementsByTagName('description')->item(0)->textContent),
			'author' => trim($application->getElementsByTagName('author')->item(0)->textContent),
			'url' => trim($application->getElementsByTagName('url')->item(0)->textContent),
			'setting' => trim($application->getAttribute('setting')) == 'true',
			'isjys' => trim($application->getElementsByTagName('isjys')->item(0)->textContent),
			'is_legao' => trim($application->getElementsByTagName('is_legao')->item(0)->textContent),
			'style' => trim($application->getElementsByTagName('style')->item(0)->textContent),
			'intype' => trim($application->getElementsByTagName('intype')->item(0)->textContent),
			'istakeover' => trim($application->getElementsByTagName('istakeover')->item(0)->textContent),
			'basic' => trim($application->getElementsByTagName('basic')->item(0)->textContent),
			'diypage' => trim($application->getElementsByTagName('diypage')->item(0)->textContent),
		);
		$manifest['application']['style']=get_pluginopen_types()[$manifest['application']['type']];
		$manifest['application']['style']=$manifest['application']['style']?:2;
		$manifest['application']['type']=$manifest['application']['isjys']?:4;
		$manifest['application']['intype']=$manifest['application']['intype'];
		$platform = $domroot->getElementsByTagName('platform')->item(0);
		if (!empty($platform)) {
			$manifest['platform'] = array(
				'subscribes' => array(),
				'handles' => array(),
				'isrulefields' => false,
				'iscard' => false,
				'supports' => array(),
				'oauth_type' => 1,
			);
			$handles = $platform->getElementsByTagName('handles')->item(0);
			if (!empty($handles)) {
				$messages = $handles->getElementsByTagName('message');
				for ($i = 0; $i < $messages->length; $i++) {
					$t = $messages->item($i)->getAttribute('type');
					if (!empty($t)) {
						$manifest['platform']['handles'][] = $t;
					}
				}
			}
			$oauth_type = $platform->getElementsByTagName('oauth')->item(0);
			if (!empty($oauth_type) && $oauth_type->getAttribute('type') == 1) {
				$manifest['platform']['oauth_type'] = 1;
			}
			$subscribes = $platform->getElementsByTagName('subscribes')->item(0);
			if (!empty($subscribes)) {
				$messages = $subscribes->getElementsByTagName('message');
				for ($i = 0; $i < $messages->length; $i++) {
					$t = $messages->item($i)->getAttribute('type');
					if (!empty($t)) {
						$manifest['platform']['subscribes'][] = $t;
					}
				}
			}
			$rule = $platform->getElementsByTagName('rule')->item(0);
			if (!empty($rule) && $rule->getAttribute('embed') == 'true') {
				$manifest['platform']['isrulefields'] = true;
			}
			$card = $platform->getElementsByTagName('card')->item(0);
			if (!empty($card) && $card->getAttribute('embed') == 'true') {
				$manifest['platform']['iscard'] = true;
			}			
			$plugins = $platform->getElementsByTagName('plugins')->item(0);
			if (!empty($plugins)) {
				$plugin_list = $plugins->getElementsByTagName('item');
				for ($i = 0; $i < $plugin_list->length; $i++) {
					$plugin = $plugin_list->item($i)->getAttribute('name');
					if (!empty($plugin)) {
						$manifest['platform']['plugin_list'][] = $plugin;
					}
				}
			}
			$plugin_main = $platform->getElementsByTagName('plugin-main')->item(0);
			if (!empty($plugin_main)) {
				$plugin_main = $plugin_main->getAttribute('name');
				if (!empty($plugin_main)) {
					$manifest['platform']['main_module'] = $plugin_main;
				}
			}
			$supports = $platform->getElementsByTagName('supports')->item(0);
			if (!empty($supports)) {
				$support_type = $supports->getElementsByTagName('item');
				for ($i = 0; $i < $support_type->length; $i++) {
					$t = $support_type->item($i)->getAttribute('type');
					if (!empty($t)) {
						$manifest['platform']['supports'][] = $t;
					}
				}
			}
		}
		$permissions = $domroot->getElementsByTagName('permissions')->item(0);
		if (!empty($permissions)) {
			$manifest['permissions'] = array();
			$entrys = $permissions->getElementsByTagName('entry');
			for ($i = 0; $i < $entrys->length; $i++) {
				$item = $entrys->item($i);
				$row = array(
					'title' => $item->getAttribute('title'),
					'permission' => $item->getAttribute('do'),
				);
				if (!empty($row['title']) && !empty($row['permission'])) {
					$manifest['permissions'][] = $row;
				}
			}
		}
		$menus = $domroot->getElementsByTagName('bindings')->item(0);
		if (!empty($menus)) {
			$moren_menus = $this->get_menus();
			if (!empty($moren_menus)) {
				$moren_menus = array_keys($moren_menus);
				$manifest['bindings'] = array();
				foreach ($moren_menus as $p) {
					$menuitem = $menus->getElementsByTagName($p)->item(0);
					$manifest['bindings'][$p] = $this->jiexi_manifest_menus($menuitem);
				}
			}
		}
		return $manifest;
	}
	public function get_menus() {
		static $menus = array(
			'cover' => array(
				'name' => 'cover',
				'title' => '入口',
				'desc' => '后端入口封面.'
			),
			'menu' => array(
				'name' => 'menu',
				'title' => '导航菜单',
				'desc' => '导航菜单, 是用于对插件的内容入口.'
			),
			'shortcut'=> array(
				'name' => 'shortcut',
				'title' => '前端快捷导航',
				'desc' => '前端快捷导航，自定义导航菜单'
			),
			'rule' => array(
				'name' => 'rule',
				'title' => '规则',
				'desc' => '自定义的一些规则回复'
			),
			'profile'=> array(
				'name' => 'profile',
				'title' => '前端会员中心',
				'desc' => '前端会员中心.是指手机端，客户端访用页面'
			),
			'function'=> array(
				'name' => 'function',
				'title' => '前端独立功能',
				'desc' => '前端独立功能, 独立方入口'
			),
			'home' => array(
				'name' => 'home',
				'title' => '前端首页',
				'desc' => '前端首页，是指手机端，客户端访用页面'
			),
			'page'=> array(
				'name' => 'page',
				'title' => '小程序入口',
				'desc' => '小程序入口的PATH'
			),
			'system_welcome' => array(
				'name' => 'system_welcome',
				'title' => '后台管理导航菜单',
				'desc' => '后台管理导航菜单，导航入口, 对系统页面的入口.',
			)
		);
		return $menus;
	}
	public function jiexi_manifest_menus($menu) {
		$return = array();
		if (!empty($menu)) {
			$call = $menu->getAttribute('call');
			if (!empty($call)) {
				$return[] = array('call' => $call);
			}
			$entrys = $menu->getElementsByTagName('entry');
			for ($i = 0; $i < $entrys->length; $i++) {
				$entryitem = $entrys->item($i);
				$direct = $entryitem->getAttribute('direct');
				$ismultilevel = $entryitem->getAttribute('multilevel');
				$item = array(
					'title' => $entryitem->getAttribute('title'),
					'do' => $entryitem->getAttribute('do'),
					'direct' => !empty($direct) && $direct != 'false' ? true : false,
					'state' => $entryitem->getAttribute('state'),
					'icon' => $entryitem->getAttribute('icon'),
					'displayorder' => $entryitem->getAttribute('displayorder'),
					'multilevel' => !empty($ismultilevel) && $ismultilevel == 'true' ? true : false,
					'parent' => $entryitem->getAttribute('parent'),
				);
				if (!empty($item['title']) && !empty($item['do'])) {
					$return[] = $item;
				}
			}
		}
		return $return;
	}
	public function support_types() {
			$support_types = array(
				'wxapp_support' => array(
					'type' => 1,
					'type_name' => '微信小程序',
					'support' => 1,
					'not_support' => 0,
					'store_type' => 1,
				),
				'account_support' => array(
					'type' => 2,
					'type_name' => '微信公众号',
					'support' => 1,
					'not_support' => 0,
					'store_type' => 1,
				),
				'welcome_support' => array(
					'type' => 3,
					'type_name' => '系统首页',
					'support' => 1,
					'not_support' => 0,
				),
				'webapp_support' => array(
					'type' => 4,
					'type_name' => 'PC',
					'support' => 1,
					'not_support' => 0,
					'store_type' => 1,
				),
				'phoneapp_support' => array(
					'type' => 5,
					'type_name' => 'APP',
					'support' => 1,
					'not_support' => 0,
					'store_type' => 1,
				),
				'aliapp_support' => array(
					'type' => 6,
					'type_name' => '支付宝小程序',
					'support' => 1,
					'not_support' => 0,
					'store_type' => 1,
				),
				'baiduapp_support' => array(
					'type' => 7,
					'type_name' => '百度小程序',
					'support' => 1,
					'not_support' => 0,
					'store_type' => 1,
				),
				'toutiaoapp_support' => array(
					'type' => 8,
					'type_name' => '头条小程序',
					'support' => 1,
					'not_support' => 0,
					'store_type' => 1,
				)
		);
		return $support_types;
	}
	public function manifestxml_check($plugin_name, $manifest) {
		if(is_string($manifest)) {
			return error('模块 mainfest.xml 配置文件有误, 具体错误内容为: ' . $manifest);
		}
		$error_msg = '';
		if(empty($manifest['application']['name'])) {
			$error_msg .= 'application-name插件名称不能为空';
		}
		if(empty($manifest['application']['identifie']) || !preg_match('/^[a-z][a-z\d_]+$/i', $manifest['application']['identifie'])) {
			$error_msg .= 'application-identifie插件标识不能为空或格式错误(仅支持字母和数字, 且只能以字母开头)';
		} elseif(strtolower($plugin_name) != strtolower($manifest['application']['identifie'])) {
			$error_msg .= 'application-identifie插件标识与模块路径名称定义不匹配';
		}
		if(empty($manifest['application']['version']) || !preg_match('/^[\d\.]+$/i', $manifest['application']['version'])) {
			$error_msg .= 'application-version插件版本号未定义或格式不正确(仅支持数字和句点)';
		}
		if($manifest['platform']['isrulefields'] && !in_array('text', $manifest['platform']['handles'])) {
			$error_msg .= '插件功能定义错误, 嵌入规则必须要能够处理文本类型消息';
		}
		if((!empty($manifest['cover']) || !empty($manifest['rule'])) && !$manifest['platform']['isrulefields']) {
			$error_msg .= '插件功能定义错误, 存在封面入口或规则入口时, 必须要嵌入规则';
		}
		if(is_array($manifest['permissions']) && !empty($manifest['permissions'])) {
			foreach($manifest['permissions'] as $permission) {
				if(trim($permission['title']) == ''  || !preg_match('/^[a-z\d_]+$/i', $permission['permission'])) {
					$error_msg .= '<br/>' . "&lt;permissions&gt;节点名称为： {$permission['title']} 的权限标识格式不正确,请检查标识名称或标识格式是否正确";
				}
			}
		}
		if (!empty($error_msg)) {
			return error('模块 mainfest.xml 配置文件有误<br/>' . $error_msg);
		}
		return true;
	}
	public function int_manifest($plugin_name) {
		if (!file_exists(ROOT_PLUGIN . $plugin_name)) {
			exi('插件文件目录不存在','error');
		}
		$manifest=array();
		$plugin=pdo_get('core_plugins',array('name'=>$plugin_name));
		$plugin['bindings']=$plugin['bindings']?json_decode($plugin['bindings'],true):'';
		$plugin['menus']=$plugin['menus']?json_decode($plugin['menus'],true):'';
		$plugin['covers']=$plugin['covers']?json_decode($plugin['covers'],true):'';
		if($plugin['bindings']){
			$manifest['bindings']=$plugin['bindings'];
		}else if($plugin['menus']){
			$manifest['bindings']['menu']=$plugin['menus'];
			$manifest['bindings']['cover']=$plugin['covers'];
		}
		$permissions=pdo_getall('core_plugin_permissions',array('plugin'=>$plugin['name']),array('plugin','action','op','title','type'));
		$install=$uninstall='';
		$tables=pdo_fetchall("SHOW TABLES LIKE '".TABLE_PRE.$plugin['name']."_%'");
		if($tables){
					foreach($tables as &$table){
						$table=array_shift($table);
						$tablename=explode('_',$table,2);
						$tablename=$tablename['1'];
						$sql=pdo_fetch('show create table '.$table);
						$sql=$sql['Create Table'];
						//将表前缀换成一般值
						$sql=str_replace("`{$table}`","`{table_pre}{$tablename}`",$sql);
						$install.="DROP TABLE IF EXISTS {table_pre}{$tablename};\n";
						$install.=$sql.";\n";
						$uninstall.="DROP TABLE IF EXISTS {table_pre}{$tablename};\n";
					}
		}
		$otables=pdo_getall('core_plugin_tables',array('plugin_name'=>$plugin['name']),array('name'),'name');		
		if($otables){
			$otables=array_keys($otables);
			foreach($otables as $table){
				$sql=pdo_fetch('show create table '.TABLE_PRE.$table);
				$sql=$sql['Create Table'];
				$sql=str_replace('`'.TABLE_PRE.$table.'`','`{table_pre}'.$table.'`',$sql);
				$install.=$sql.";\n";
				$uninstall.="DROP TABLE IF EXISTS {table_pre}{$table};\n";
			}
		}
		$indata=pdo_getall('core_plugin_install_data',array('plugin_name'=>$plugin['name']),array('table'),'table');
		if($indata){
			$indata=array_keys($indata);
			foreach($indata as $iv){
				if(!pdo_tableexists($iv)){
					continue;
				}
				$tables=pdo_getall($iv);
				$info = "-- ----------------------------\r\n";
				$info .= "-- Records for `".$iv."`\r\n";
				$info .= "-- ----------------------------\r\n";
				$sqldump .= $info;
				foreach($tables as $tv){
					$sqlStr = "INSERT INTO `".TABLE_PRE.$iv."` VALUES (";
					$row=array_values($tv);
					foreach($row as $zd){
						$sqlStr .= "'".$zd."', ";
					}
					//去掉最后一个逗号和空格
					$sqlStr = substr($sqlStr,0,strlen($sqlStr)-2);
					$sqlStr .= ");\r\n";
					$sqldump .= $sqlStr;
				}
				$install.=$sqldump;
			}
		}
		$old_plugins=pdo_get('core_old_plugins',array('name'=>$plugin['name']));
		$setting=$old_plugins['setting'];
		$manifest['install']=$install;
		$manifest['uninstall']=$uninstall;
		$manifest['application']['identifie']=$plugin['name'];
		$manifest['application']['name']=$plugin['title'];
		$manifest['application']['version']=$plugin['version'];
		$manifest['application']['style']=$plugin['style'];
		$manifest['application']['intype']=$plugin['intype'];
		$manifest['application']['istakeover']=$plugin['istakeover'];
		$manifest['application']['basic']=$plugin['basic'];
		$manifest['application']['diypage']=$plugin['diypage'];
		$manifest['application']['ability']=$plugin['ability'];
		$manifest['application']['description']=$plugin['description'];
		$manifest['application']['author']=$plugin['author'];
		$manifest['application']['url']=$plugin['url'];
		$manifest['application']['setting']=$setting;
		$manifest['application']['isjys']=$plugin['type']!=4?true:false;
		$manifest['application']['is_legao']=$plugin['is_legao']?true:false;
		$manifest['application']['need_menu']=$old_plugins['need_menu'];
		$manifest['platform']['subscribes']=$subscribes?:array();
		$manifest['platform']['handles']=$handles?:array();
		$manifest['platform']['rule']=$plugin['isrulefields'];
		$manifest['platform']['card']=$plugin['iscard'];
		$manifest['permissions']=$permissions?:array();
		$manifestxml=$this->manifestxml($manifest);
		return $manifestxml;
	}
	public function manifestxml($manifest) {
		$setting = $manifest['application']['setting'] ? 'true' : 'false';
		$subscribes = '';
		foreach($manifest['platform']['subscribes'] as $sv) {
			$subscribes .= "\r\n\t\t\t<message type=\"{$sv}\" />";
		}
		$handles = '';
		foreach($manifest['platform']['handles'] as $hv) {
			$handles .= "\r\n\t\t\t<message type=\"{$hv}\" />";
		}
		$rule = $manifest['platform']['rule'] ? 'true' : 'false';
		$card = $manifest['platform']['card'] ? 'true' : 'false';
		if(is_array($manifest['permission']) && !empty($manifest['permission'])) {
			$permissions = '';
			foreach($manifest['permission'] as $entry) {
				$piece .= "\r\n\t\t\t<entry title=\"{$entry['title']}\" do=\"{$entry['permission']}\" />";
			}
			$permissions .= $piece;
		}
		$bindings = '';
		$menus = $this->get_menus();
		foreach($menus as $key => $row) {
			if(is_array($manifest['bindings'][$key]) && !empty($manifest['bindings'][$key])) {
				$piece = "\r\n\t\t<{$key}>";
				foreach($manifest['bindings'][$key] as $entry) {
					$direct = $entry['direct'] ? 'true' : 'false';
					$do=$entry['name']?$entry['name']:$entry['do'];
					$piece .= "\r\n\t\t\t<entry title=\"{$entry['title']}\" do=\"{$do}\" state=\"{$entry['state']}\" direct=\"{$direct}\" />";
				}
				$piece .= "\r\n\t\t</{$key}>";
				$bindings .= $piece;
			}
		}
		$tpl = <<<TPL
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns="https://s.jinyunweb.com" versionCode="1.0">
	<application setting="{$setting}">
		<name><![CDATA[{$manifest['application']['name']}]]></name>
		<isjys><![CDATA[{$manifest['application']['isjys']}]]></isjys>
		<basic><![CDATA[{$manifest['application']['basic']}]]></basic>
		<style><![CDATA[{$manifest['application']['style']}]]></style>
		<intype><![CDATA[{$manifest['application']['intype']}]]></intype>
		<istakeover><![CDATA[{$manifest['application']['istakeover']}]]></istakeover>
		<is_legao><![CDATA[{$manifest['application']['is_legao']}]]></is_legao>
		<identifie><![CDATA[{$manifest['application']['identifie']}]]></identifie>
		<version><![CDATA[{$manifest['application']['version']}]]></version>
		<ability><![CDATA[{$manifest['application']['ability']}]]></ability>
		<description><![CDATA[{$manifest['application']['description']}]]></description>
		<diypage><![CDATA[{$manifest['application']['diypage']}]]></diypage>
		<author><![CDATA[{$manifest['application']['author']}]]></author>
		<url><![CDATA[{$manifest['application']['url']}]]></url>
	</application>
	<platform>
		<subscribes>{$subscribes}
		</subscribes>
		<handles>{$handles}
		</handles>
		<rule embed="{$rule}" />
		<card embed="{$card}" />
	</platform>
	<bindings>{$bindings}
	</bindings>
	<permissions>{$permissions}
	</permissions>
	<install><![CDATA[{$manifest['install']}]]></install>
	<uninstall><![CDATA[{$manifest['uninstall']}]]></uninstall>
	<upgrade><![CDATA[{$manifest['upgrade']}]]></upgrade>
</manifest>
TPL;
		return ltrim($tpl);
	}
}